﻿#region
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Net;
using System.Windows.Forms;

#endregion

namespace TumblrDownloader
{
    public partial class MainForm : Form
    {
        private readonly WebClient _web = new WebClient();

        public MainForm()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (DesignMode)
                return;

#if DEBUG
            txtDownloadFolder.Text = @"D:\Desktop\wanimal1983";
#else
            txtDownloadFolder.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
#endif
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            PageLoadingForm form = new PageLoadingForm(txtTumblrId.Text);
            if (form.ShowDialog() != DialogResult.OK)
                return;

            Cursor = Cursors.WaitCursor;
            grbCommand.Enabled = false;

            bgwWorker.RunWorkerAsync(form.Srcs);
        }

        private void bgwWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            List<string> srcs = (List<string>) e.Argument;
            for (int i = 1; i <= srcs.Count; i++)
            {
                var fileName = Path.GetFileName(srcs[i]);
                var filePath = Path.Combine(txtDownloadFolder.Text, fileName);

                FileInfo file = new FileInfo(filePath);
                if (file.Exists == false || file.Length == 0)
                    _web.DownloadFile(srcs[i], filePath);

                bgwWorker.ReportProgress(0, new ProgressInfo(i, srcs.Count, filePath));
            }

            e.Result = srcs;
        }

        private void bgwWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            List<string> srcs = (List<string>) e.Result;
            MessageBox.Show(string.Format("총 {0:N0} 장의 이미지를 다운로드하였습니다.", srcs.Count));

            grbCommand.Enabled = true;
            Cursor = Cursors.Arrow;
        }

        private void bgwWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ProgressInfo info = (ProgressInfo) e.UserState;

            lblProgress.Text = string.Format("{0:N0} / {1:N0}", info.Index, info.TotalCount);
            prbProgress.Value = info.Percent;

            try
            {
                if (ptbImage.Image != null)
                    ptbImage.Image.Dispose();

                ptbImage.Image = Image.FromFile(info.FilePath);
            }
            catch
            {
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (fbdDownload.ShowDialog() != DialogResult.OK)
                return;

            txtDownloadFolder.Text = fbdDownload.SelectedPath;
        }

        private class ProgressInfo
        {
            public ProgressInfo(int index, int totalCount, string filePath)
            {
                Index = index;
                TotalCount = totalCount;
                FilePath = filePath;
            }

            public int Index { get; private set; }
            public int TotalCount { get; private set; }
            public string FilePath { get; private set; }

            public int Percent
            {
                get
                {
                    if (TotalCount == 0)
                        return 0;

                    return (int) ((float)Index / TotalCount * 100);
                }
            }
        }
    }
}